package com.xq.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.gson.GsonBuilder;
import com.jfinal.core.Controller;
import com.jfinal.log.Logger;
import com.jfinal.upload.UploadFile;
import com.xq.common.Constants;
import com.xq.common.utils.XiaoQuUtils;
import com.xq.controller.XQHttpClinet.Request;
import com.xq.controller.XQHttpClinet.Result;
import com.xq.model.Shop;


public class ShopController extends Controller {

	private static Logger logger = Logger.getLogger(ShopController.class);
	private final static String SHOP_GEO_TABLE_ID_IN_BAIDU_CLOUD = "67908";

	@SuppressWarnings("rawtypes")
	public void nearby() {
		//http://api.map.baidu.com/geosearch/v3/nearby?geotable_id=67941&ak=ihoD6xGDexQaQASG1ZItZZ2F&
			//location=121.240864,31.06634&coord_type=3&radius=20000&sortby=distance:1&page_size=30&tags=xiaoqu
		String location = getPara("location");
		if (Strings.isNullOrEmpty(location))
		{
			Map<String, Object> xiaoqu = (Map<String, Object>)((Map)this.getAttr("user")).get("xiaoqu");
			location = xiaoqu.get("longitude") + ", " +  xiaoqu.get("latitude");
		}
		String page = this.getPara("page");
		String pageSize = this.getPara("pageSize");
		String tags = this.getPara("tags");
		Request request = new Request();
		request.setUrl(Constants.URL_BAIDU_CLOUD_POI_NEARBY)
				.addPara("geotable_id", SHOP_GEO_TABLE_ID_IN_BAIDU_CLOUD)
				.addPara("ak", Constants.BAIDU_CLOUDE_ACCESS_KEY)
				.addPara("location", location)
				.addPara("coord_type", String.valueOf(3))
				.addPara("radius", String.valueOf(2000))
				.addPara("sortby", "distance:-1")
				.addPara("page_index", Strings.isNullOrEmpty(page)? "0": page)
				.addPara("page_size", Strings.isNullOrEmpty(page)? "10": pageSize);
		if (!Strings.isNullOrEmpty(tags))
		{
			request.addPara("tags", tags);
		}
		XQHttpClinet client = new XQHttpClinet();
		Result<String> result = client.execute(request);
		
		//response is like below
		/*
		{
		    "status": 0,
		    "total": 1,
		    "size": 1,
		    "contents": [{
		        "address": "\u8c37\u9633\u5317\u8def2399\u5f04\u6885\u5bb6\u6d5c\u8def1493\u5f04",
		        "city": "\u4e0a\u6d77\u5e02",
		        "create_time": 1402546867,
		        "district": "\u677e\u6c5f\u533a",
		        "geotable_id": 67941,
		        "location": [121.242148, 31.054949],
		        "modify_time": 1402547339,
		        "name": "\u4e0a",
		        "province": "\u4e0a\u6d77\u5e02",
		        "tags": "test xiaoqu xiaoqu2",
		        "title": "\u5fa1",
		        "uid": 249149744,
		        "coord_type": 3,
		        "type": 0,
		        "distance": 1267,
		        "weight": 0
		    }]
		}*/
		if (isSuccess(result))
		{
			List<Long> lbsIdList = new ArrayList<Long>();
			Map<Long, Number> distanceMap = new HashMap<Long, Number>();
			Map map = new GsonBuilder().create().fromJson(result.getData(), Map.class);
			int size = ((Double)map.get("size")).intValue();
			int total =  ((Double)map.get("total")).intValue();
			if (size > 0)
			{
				List content = (List)map.get("contents");
				for(Object object: content)
				{
					Map poi = (Map)object;
					long id = ((Double)poi.get("uid")).longValue();
					int distance = ((Double)poi.get("distance")).intValue();
					lbsIdList.add(id);
					distanceMap.put(id, distance);
				}
			}
			
			List<Shop> shopList = Shop.dao.findByLBSIdList(lbsIdList);
			
			Map<String, Object> responseObj = new HashMap<String, Object>();
			List<Object> shopMapList = new ArrayList<Object>();
			for(Shop shop: shopList)
			{
				long lbsId = shop.getLong("lbsId");
				//shop.set("distance", distanceMap.get(lbsId));
				Map shopAttrs = shop.cloneAttrs();
				shopAttrs.put("distance", distanceMap.get(lbsId));
				shopMapList.add(shopAttrs);
			}
			responseObj.put("total", total);
			responseObj.put("size", shopMapList.size());
			responseObj.put("shops", shopMapList);
			XQResponse response = new XQResponse(XQResponse.STATUS_SUCCESS
					, "success", new GsonBuilder()
			//.registerTypeAdapter(Integer.class, new GsonNumberToStringAdaptor())
			//.registerTypeAdapter(Long.class, new GsonNumberToStringAdaptor())
			.create()
			.toJson(responseObj));
			renderJson(response);
		} else {
			renderJson(new XQResponse(XQResponse.STATUS_EXCEPTION));
		}
	}

	public void create() {
		List<UploadFile> uploadFiles = getFiles();
		List<String> images = new ArrayList<String>();
		for (UploadFile uploadFile : uploadFiles) {
			String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) 
					+ "." + XiaoQuUtils.getFileExtension(uploadFile.getOriginalFileName());
			String destFilePath = Constants.SHOPT_PATH + File.separator
					+ fileName;
			logger.debug(getPara("name") + " shop image path:" + destFilePath);
			try {
				FileUtils
						.moveFile(uploadFile.getFile(), new File(destFilePath));
			} catch (IOException e) {
				logger.debug(e.getMessage());
			}
			images.add(fileName);
		}
		String name = getPara("name");
		String address = getPara("address");
		String phones = getPara("phones");
		String detail = getPara("detail");
		String longitude = getPara("location").split(",")[0].trim();
		String latitude = getPara("location").split(",")[1].trim();
		String tags = getPara("tags");
		
		Request request = new Request();
		request.setUrl(Constants.URL_BAIDU_CLOUD_POI_CREATE).setMethod(XQHttpClinet.METHOD_POST)
				.addPara("geotable_id", SHOP_GEO_TABLE_ID_IN_BAIDU_CLOUD)
				.addPara("ak", Constants.BAIDU_CLOUDE_ACCESS_KEY)
				.addPara("longitude", longitude)
				.addPara("latitude", latitude)
				.addPara("coord_type", String.valueOf(3))
				.addPara("title", name)
				.addPara("address", address)
				.addPara("tags", tags)
				.addPara("name", name); //扩展字段，店面名称
		XQHttpClinet client = new XQHttpClinet();
		Result<String> result = client.execute(request);
		//response should be like '{"status":0,"id":249086468,"message":"\u6210\u529f"}'
		String lbsId = "0";
		if (isSuccess(result))
		{
			Map map = new GsonBuilder().create().fromJson(result.getData(), Map.class);
			lbsId = ((Double)map.get("id")).intValue() + "";
			logger.debug(name + "(" + longitude + ", "+ latitude+  ") is added to baidu lbs and id is " + lbsId);
		} else {
			renderJson(new XQResponse(XQResponse.STATUS_ADD_SHOP_TO_LBS_FAILED));
			return;
		}
		Shop shop = new Shop();
		shop.set("name", name);
		shop.set("address", address);
		shop.set("phones", phones);
		shop.set("detail", detail);
		shop.set("images", Joiner.on(",").join(images));
		shop.set("longitude", Double.parseDouble(longitude));
		shop.set("latitude", Double.parseDouble(latitude));
		shop.set("tags", tags);
		shop.set("lbsId", Long.valueOf(lbsId));
		shop.save();
		renderJson(new XQResponse(XQResponse.STATUS_SUCCESS, "success", ""));
	}
	
	public void update()
	{
		
	}
	
	public void delete()
	{
		String lbsId = getPara("lbsId");
		Shop.dao.deleteByLBSId(Long.valueOf(lbsId));
		Request request = new Request();
		request.setUrl(Constants.URL_BAIDU_CLOUD_POI_NEARBY).setMethod("post")
		
				.addPara("geotable_id", SHOP_GEO_TABLE_ID_IN_BAIDU_CLOUD)
				.addPara("ak", Constants.BAIDU_CLOUDE_ACCESS_KEY)
				.addPara("id", lbsId);
		XQHttpClinet client = new XQHttpClinet();
		client.execute(request);
		renderJson(new XQResponse(XQResponse.STATUS_SUCCESS));
	}

	private boolean isSuccess(Result<String> result) {
		if (result.getHttpException() != null
				|| result.getResponseParserException() != null) {
			return false;
		}
		if (result.getHttpStatus() > 300) {
			return false;
		}
		String response = result.getData();
		Map map = new GsonBuilder().create().fromJson(response, Map.class);
		if (((Double) map.get("status")).intValue() != 0) {
			return false;
		}
		return true;
	}

	
	public static void main(String[] args) {
		Request request = new Request();
		String location = "121.240864,31.06634";
       // String tags = "";
        String page = "0";
        String pageSize = "10";
        
		request.setUrl(Constants.URL_BAIDU_CLOUD_POI_NEARBY).setMethod("get")
				.addPara("geotable_id", SHOP_GEO_TABLE_ID_IN_BAIDU_CLOUD)
				.addPara("ak", Constants.BAIDU_CLOUDE_ACCESS_KEY)
				.addPara("location", location)
				.addPara("coord_type", String.valueOf(3))
				.addPara("radius", String.valueOf(2000))
				.addPara("sortby", "distance:-1")
				//.addPara("tags", tags)
				.addPara("page_index", Strings.isNullOrEmpty(page)? "0": page)
				.addPara("page_size", Strings.isNullOrEmpty(page)? "10": pageSize);
		
		XQHttpClinet client = new XQHttpClinet();
		Result<String> result = client.execute(request);
		
		//response is like below
		/*
		{
		    "status": 0,
		    "total": 1,
		    "size": 1,
		    "contents": [{
		        "address": "\u8c37\u9633\u5317\u8def2399\u5f04\u6885\u5bb6\u6d5c\u8def1493\u5f04",
		        "city": "\u4e0a\u6d77\u5e02",
		        "create_time": 1402546867,
		        "district": "\u677e\u6c5f\u533a",
		        "geotable_id": 67941,
		        "location": [121.242148, 31.054949],
		        "modify_time": 1402547339,
		        "name": "\u4e0a",
		        "province": "\u4e0a\u6d77\u5e02",
		        "tags": "test xiaoqu xiaoqu2",
		        "title": "\u5fa1",
		        "uid": 249149744,
		        "coord_type": 3,
		        "type": 0,
		        "distance": 1267,
		        "weight": 0
		    }]
		}*/
		if (true)
		{
			List<Long> lbsIdList = new ArrayList<Long>();
			Map<Long, Number> distanceMap = new HashMap<Long, Number>();
			Map map = new GsonBuilder().create().fromJson(result.getData(), Map.class);
			int size = ((Double)map.get("size")).intValue();
			if (size > 0)
			{
				List content = (List)map.get("contents");
				for(Object object: content)
				{
					Map poi = (Map)object;
					long id = ((Double)poi.get("uid")).longValue();
					int distance = ((Double)poi.get("distance")).intValue();
					lbsIdList.add(id);
					distanceMap.put(id, distance);
				}
			}
		} else {
		}
	}
}
